package vip.zhenzicheng.nettybasic.checkread;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;

/**
 * @author zhenzicheng
 * @date 2022-06-12 19:51
 */
public class EchoClientCRHandler extends SimpleChannelInboundHandler<ByteBuf> {

  private static final Logger LOG = Logger.getLogger(EchoClientCRHandler.class.getSimpleName());

  @Override
  protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {
    LOG.info("client accept:" + byteBuf.toString(StandardCharsets.UTF_8));
    ctx.close();
  }

  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    ByteBuf msg;
    // 发送较小的报文多次
    String requestSmall = "small" + System.getProperty("line.separator");
    for (int i = 0; i < 100; i++) {
      msg = Unpooled.buffer(requestSmall.length());
      msg.writeBytes(requestSmall.getBytes());
      ctx.writeAndFlush(msg);
    }
    LOG.info("client send small message.");
  }
}
